import { useEffect, useRef, useState } from 'react';
// eslint-disable-next-line import/no-extraneous-dependencies
import { useDebounceFn } from 'ahooks';
import { AutoComplete, Button, Col, DatePicker, Form, Input, InputNumber, Modal, Row, Select, Space } from 'antd';
import { environmentEnum, taskEnum } from '@/utils/data';
import Icon from '@/components/layout/Icon';
import { getUserMangeList } from '@/request/userMange';

import dayjs from 'dayjs';
import s from './index.module.css';

const { TextArea } = Input;
const { RangePicker } = DatePicker;

export default function SchedulePlanRight({ handlePlan, confirmNode, submitData, lockInfo }) {
  const dateFormat = 'YYYY-MM-DD';
  const scroll: any = useRef();
  const testArea: any = useRef();
  let t: any = null;
  const [form] = Form.useForm();
  const [developerIds, setDeveloperIds] = useState([]);
  const options = [
    { value: '1', label: '1' },
    { value: '2', label: '2' },
    { value: '4', label: '4' },
    { value: '6', label: '6' },
    { value: '10', label: '10' },
    { value: '20', label: '20' },
    { value: '30', label: '30' },
  ];
  const developerItemInit = {
    developerId: undefined,
    developerName: undefined,
    taskList: [{ taskType: undefined, time: undefined, taskCost: undefined, taskStartTime: undefined, taskEndTime: undefined }],
  };
  const taskItemInit = { taskType: undefined, time: undefined, taskCost: undefined, taskStartTime: undefined, taskEndTime: undefined };

  // 获取开发人选择值
  const getDeveloperId = (value: any, option: any, i) => {
    let id: string | undefined = '';
    let name = '';
    if (!option.label) {
      name = value;
      id = undefined;
    } else {
      name = option.label;
      id = option.value;
    }
    const data = form.getFieldValue('developerList');
    data[i].developerName = name;
    data[i].developerId = id;
    form.setFieldsValue({ developerList: data });
  };

  // 获取开发人搜索数据
  const getDeveloperList = async (value: any) => {
    try {
      const res: any = await getUserMangeList({ name: value });
      const data = res.data.map((item) => ({
        label: item.name,
        value: item._id,
      }));
      setDeveloperIds(data);
    } catch (e) {
      console.log(e);
    }
  };

  const { run } = useDebounceFn(
    (v) => {
      getDeveloperList(v);
    },
    {
      wait: 500,
    },
  );

  // 处理时间
  const handleTime = (time: any, index, i) => {
    const data = form.getFieldValue('developerList');
    const item = data[index].taskList.map((it, itI) => {
      if (itI === i) {
        return { ...it, taskStartTime: time[0], taskEndTime: time[1] };
      }
      return it;
    });
    data[index].taskList = item;
    form.setFieldsValue({ developerList: data });
  };

  // 复制
  const handleCopy = (i: number) => {
    const data = form.getFieldValue('developerList');
    const newData = { ...data[i] };
    newData.developerId = undefined;
    newData.developerName = undefined;
    data.splice(i + 1, 0, newData);
    form.setFieldsValue({ developerList: data });
    console.log(data, i);
  };

  // form表单值变化
  const { run: handleFormChange } = useDebounceFn(
    () => {
      const data = form.getFieldsValue();
      handlePlan({ ...data, timeNodes: submitData?.timeNodes });
    },
    {
      wait: 500,
    },
  );

  // 添加人员
  const handleAdd = (addFn) => {
    addFn(developerItemInit);
    t = setTimeout(() => {
      const { scrollHeight }: { scrollHeight: number } = scroll.current;
      scroll.current.scrollTo({
        top: scrollHeight - testArea.current.scrollHeight - 200,
        behavior: 'smooth',
      });
    }, 0);
  };

  // 删除人员
  const handleDelete = (removeFn, name) => {
    Modal.confirm({
      title: '提示',
      closable: true,
      icon: null,
      okText: '确认',
      cancelText: '取消',
      content: <div>确认删除此排期卡片吗？</div>,
      onOk() {
        removeFn(name);
      },
      onCancel() {},
    });
  };

  // 时间处理
  const handleTimeChange = (time: string) => {
    const dayjsData = time ? dayjs(time, dateFormat) : undefined;
    return dayjsData;
  };

  // 处理数据
  const handleData = (list = []) => {
    const data = list.map((it: any) => {
      return {
        ...it,
        taskList: it.taskList.map((sub) => ({
          ...sub,
          taskType: sub.taskType ? String(sub.taskType) : undefined,
          taskStartTime: sub.taskStartTime,
          taskEndTime: sub.taskEndTime,
          time: [handleTimeChange(sub.taskStartTime), handleTimeChange(sub.taskEndTime)],
        })),
      };
    });
    return data;
  };

  useEffect(() => {
    const obj = submitData || {};
    const data = {
      ...obj,
      developerList: handleData(obj.developerList),
    };
    form.setFieldsValue(data);

    return () => {
      clearTimeout(t);
    };
  }, [submitData]);

  return (
    <div className={s.schedulePlanRight}>
      <Form form={form} onValuesChange={handleFormChange} disabled={lockInfo?.isLock} colon={false}>
        <Row gutter={[20, 0]} className={s.schedulePlanRightH}>
          <Col span={9.5}>
            <Form.Item label="技术Owner" name="developOwner">
              <Input placeholder="请输入" style={{ width: '230px' }} />
            </Form.Item>
          </Col>
          <Col span={9.5}>
            <Form.Item label="提测环境" name="developEnv">
              <Select options={environmentEnum} placeholder="请选择" style={{ width: '242px' }} />
            </Form.Item>
          </Col>
          <Col span={4}>
            <Button type="primary" onClick={confirmNode}>
              确认节点并提交
            </Button>
          </Col>
        </Row>
        <div className={s.scrollContent} ref={scroll}>
          <Form.List name="developerList" initialValue={[developerItemInit]}>
            {(developerList, { add, remove }) => (
              <>
                <div className={s.developerList}>
                  {developerList.map(({ key, name, ...restField }, index) => (
                    <div key={key} className={s.developerItemContent}>
                      <div className={s.developerItem}>
                        <div className={s.developerItemLeft}>
                          <Form.Item {...restField} name={[name, 'developerName']}>
                            <AutoComplete
                              // eslint-disable-next-line @typescript-eslint/no-misused-promises
                              onSearch={run}
                              onChange={(value, option) => getDeveloperId(value, option, index)}
                              onSelect={(value, option) => getDeveloperId(value, option, index)}
                              options={developerIds}
                              style={{ width: '110px' }}
                              placeholder="请输入姓名"
                            />
                          </Form.Item>
                          <Form.Item name={[name, 'developerId']} />
                        </div>
                        <div>
                          <Form.List name={[name, 'taskList']} initialValue={[taskItemInit]}>
                            {(taskList, { add: addtask, remove: removetask }) => (
                              <div className={s.developerItemRight}>
                                {taskList.map((taskItem: any, i) => (
                                  <Space key={`taskItme${taskItem.key as string}`} className={i === taskList.length - 1 ? '' : s.developerItemRightI}>
                                    <Form.Item {...taskItem.restField} name={[taskItem.name, 'taskType']}>
                                      <Select options={taskEnum} placeholder="选择任务类型" style={{ width: '130px' }} />
                                    </Form.Item>
                                    <Form.Item name={[taskItem.name, 'taskStartTime']} noStyle />
                                    <Form.Item {...taskItem.restField} name={[taskItem.name, 'time']}>
                                      <RangePicker style={{ width: '260px' }} format={dateFormat} onChange={(_, v) => handleTime(v, index, i)} />
                                    </Form.Item>
                                    <Form.Item name={[taskItem.name, 'taskEndTime']} noStyle />
                                    <Form.Item {...taskItem.restField} name={[taskItem.name, 'taskCost']}>
                                      <AutoComplete options={options} placeholder="请输入" style={{ width: '90px' }} />
                                    </Form.Item>
                                    <Form.Item style={{ width: '28px' }}>工时</Form.Item>
                                    <Form.Item>
                                      <div className="flex">
                                        {taskList.length > 1 && !lockInfo?.isLock && (
                                          <Icon src="/images/removeR.svg" width={18} height={18} style={{ marginRight: '11px' }} onClick={() => removetask(taskItem.name)} />
                                        )}
                                        {i === taskList.length - 1 && !lockInfo?.isLock && <Icon src="/images/addR.svg" width={18} height={18} onClick={() => addtask(taskItemInit)} />}
                                      </div>
                                    </Form.Item>
                                  </Space>
                                ))}
                              </div>
                            )}
                          </Form.List>
                        </div>
                      </div>
                      <div className={s.developerItemActionC}>
                        <div className={s.developerItemAction}>
                          {!lockInfo?.isLock && <Icon src="/images/copy.svg" width={32} height={32} style={{ marginBottom: '10px' }} onClick={() => handleCopy(index)} />}
                          {developerList.length > 1 && !lockInfo?.isLock && <Icon src="/images/removeRed.svg" width={32} height={32} onClick={() => handleDelete(remove, name)} />}
                        </div>
                      </div>
                    </div>
                  ))}
                </div>
                <Form.Item className={s.addUser}>
                  <Button className="flex" type="primary" onClick={() => handleAdd(add)} icon={<Icon src="/images/add.png" width={16} height={16} style={{ marginRight: '4px' }} />}>
                    添加人员排期
                  </Button>
                </Form.Item>
              </>
            )}
          </Form.List>
          <div ref={testArea}>
            <Form.Item label="测试范围" name="testArea">
              <TextArea placeholder="请输入测试范围" style={{ width: '722px' }} autoSize={{ minRows: 4 }} />
            </Form.Item>
          </div>
        </div>
      </Form>
    </div>
  );
}
